<?php

namespace app\api\controller\ec;

use app\common\controller\Api;
use app\common\exception\UploadException;
use think\Config;
use think\Hook;
use think\Db;

/**
 * 公共接口
 * 第一步:先添加客户 到ec
 * 第二步:根据客户手机号 获取CrmId
 * 第三步：根据CrmId 获取客户信息
 */
class Ecautotuisong extends Ecbase {

    public function _initialize() {
        parent::_initialize();
    }
    
    /**
     * 废弃客户入库  while
     */
    public function tuisongFeiqiKehu(){
        
        while (true){
            $status = db('ec_zhongzhuan_config')->where('name','baiying_to_ec_status')->value('value');
            if(empty($status)){
                sleep(5);
                echo date('Y-m-d H:i:s') . "[status]\r\n";
                continue;
            }
            
            
            $today_start_time = strtotime("today");    
            $now_time = time();
            if(($now_time < $today_start_time + 12 * 3600) || ($now_time > $today_start_time + 13 * 3600 && $now_time < $today_start_time + 18 * 3600)){
                echo date('Y-m-d H:i:s');
                sleep(3);
                continue;
            }
            
           
            
            
            $controller = '\app\common\controller\zhongzhuan\Autoassigncd';
            $param = [];
            $data = call_user_func_array(array($controller, 'startAssign'),array($param));
            
            // usleep() 函数延迟执行当前脚本若干微秒（一微秒等于一百万分之一秒）。 延迟5秒
            sleep(5);
        }
        
    }



    /**
     * A B类客户入库
     */
    public function tuisongABKehu(){
       
        while (true){
//            $today_start_time = strtotime("today");           
//            if((time() > $today_start_time + 18 * 3600) || (time() < $today_start_time + 8 * 3600)){
//                usleep(5000000);
//                continue;
//            }
            $status = db('ec_zhongzhuan_config')->where('name','baiying_to_ec_status')->value('value');
            if(empty($status)){
                sleep(5);
                echo date('Y-m-d H:i:s') . "[status] \r\n";
                continue;
            }
//            sleep(5);
            
            $timestamp = strtotime("today");
            $list = db('ec_assign_kehu')->where('createtime','>',$timestamp)->where('status','<>',2)->order('createtime desc')->limit(1)->select();
            
//            $list = db('ec_assign_kehu')->where('id','7')->where('status','<>',2)->order('createtime desc')->limit(1)->select();


            foreach ($list as $key=>$value){

                if(empty($value['auto_assign']))                continue;
                //$status 0 暂停   1 分配中  2 分配完成
                $assing_kehu_detail = db('ec_assign_kehu_detail')->field('SUM(people - success_people) daifenpei')->where('people','>',0)->where('assign_id',$value['id'])->where('assign_status',1)->find();
           
                
                $kehu_list = array();
                $daifenpei = empty($assing_kehu_detail['daifenpei']) ? 0 : $assing_kehu_detail['daifenpei'];
                
                
                if(empty($daifenpei)) continue;
                qqq('tuisongABKehu_1',date('Y-m-d H:i:s'));
                
                $assign_detail_success_data = db('ec_assign_kehu_detail')->alias('a')
                        ->join('ec_user u','a.user_id = u.id')
                        ->where('a.people','>',0)
                        ->where('u.is_shangban',1)
                        ->where('a.assign_id',$value['id'])
                        ->where('a.assign_status',1)->column('a.user_id,a.success_people,a.people');

                $limit = $daifenpei > 100 ? 100 :$daifenpei;
                qqq('tuisongABKehu_2',date('Y-m-d H:i:s'));
             

                $kehu_list= db(getBaiYingDataTable())->field('id byid,callJobId,customerTelephone,customerName,callInstanceId,yixiang_txt,yixiang_value,startTime,duration')->where([
                    'yixiang_value'=>['in',['A','B']],
//                    'createtime'=>['>',$timestamp],
                    'startTime'=>['>',$timestamp  * 1000],
                    'status'=>0
                ])->limit($limit)->order('startTime asc')->select();
                
                qqq('tuisongABKehu_3',date('Y-m-d H:i:s'));
                
                if(empty($kehu_list) || empty($assign_detail_success_data)) continue;
                
                
                $insert_data = [];
                $task_phone_update = [];                
                $success_assign_count = 0;
                
               
                foreach ($kehu_list as $kehu_info){     
                    qqq('tuisongABKehu_4',date('Y-m-d H:i:s'));
                    $user_id = db('ec_aiuser_to_ecuser')->where([
                        'mobile'=>$kehu_info['customerTelephone'],
                        'ecid'=>['>',0]
                    ])->order('id desc')->value('ecid');
                   qqq('tuisongABKehu_5',date('Y-m-d H:i:s'));
//                    $user_id = '';
//                   if(!empty($assign_detail_success_data[$user_id]) &&  $assign_detail_success_data[$user_id]['success_people'] > $assign_detail_success_data[$user_id]['people']){
//                       $user_id = '';                       
//                   }
                   
                   if(empty($assign_detail_success_data[$user_id])){
                       $user_id = '';
                   }
                   
                   $controller = '\app\common\controller\zhongzhuan\Autoassign';
                    if(empty($user_id)){
                        $result = call_user_func_array(array($controller, 'getAssingUserId'),array(['list'=>$assign_detail_success_data]));
                        qqq('tuisongABKehu_6',date('Y-m-d H:i:s'));
                        $assign_detail_success_data = $result['list'];
                        $user_id = $result['user_id'];
                    }
                    
                    
                    if(empty($user_id)){
                        
                        break;
                    } 
                    
                    
                    $param = ['assign_id'=>$value['id'],'kehu_info'=>$kehu_info,'user_id'=>$user_id];
                    $assign_data = call_user_func_array(array($controller, 'startAssign'),array($param));  
                    qqq('tuisongABKehu_7',date('Y-m-d H:i:s'));
                    if(!empty($assign_data)){
                        $success_assign_count =  $success_assign_count  + 1;
                        $task_phone_update[] = $assign_data['byid'];
                        $insert_data[] = $assign_data;
                        $assign_detail_success_data[$user_id]['success_people']=  $assign_detail_success_data[$user_id]['success_people'] + 1;
                    }
                     qqq('tuisongABKehu_8',date('Y-m-d H:i:s'));

                }
                
           
             
                
                try{
                    qqq('tuisongABKehu_9',date('Y-m-d H:i:s'));
                    Db::startTrans();
                     
                    foreach ($assign_detail_success_data as $us_key=>$us_value){  
                        $save_data = [];
                        $save_data['success_people'] = $us_value['success_people'];
                        if($us_value['success_people'] >= $us_value['people']){
                            $save_data['assign_status'] = 2;
                        }
                        db('ec_assign_kehu_detail')->where(['user_id'=>$us_key,'assign_id'=>$value['id']])->update($save_data);
                    }

                    db('ec_aiuser_to_ecuser')->insertAll($insert_data);
                    db(getBaiYingDataTable())->where('id','in',$task_phone_update)->setField('status',1);
                    $daituisong_count  = $value['daituisong_count'] + $success_assign_count;
                    

                    if($daituisong_count >= $value['count']){             
                        db('ec_assign_kehu')->where('id',$value['id'])->update(['daituisong_count'=>$daituisong_count,'status'=>2]);
                    }else{
                         db('ec_assign_kehu')->where('id',$value['id'])->update(['daituisong_count'=>$daituisong_count,'status'=>1]);
                    }
                    
                    Db::commit();
                    qqq('tuisongABKehu_10',date('Y-m-d H:i:s'));
                }catch(\Exception $e){
                    qqq('tuisongABKehu',$e->getMessage());
                    Db::rollback();
                }
                
                
                
                usleep(1000000);

            }
            
        }
        
               
    }
        



    /** 
     * 推送客户 
     */
    public function addCustomer(){
        while (true){
            $list = db('ec_aiuser_to_ecuser')->limit(50)->order('id asc')->where(['status'=>0])->select();
        
            if(empty($list)){
//                usleep(5000000);
                continue;
            }
            $end_list =  [];
            $org_kehu_list = [];
            foreach ($list as $value){
                $content = json_decode($value['content'],true);
                $end_list[] = $content;
                $org_kehu_list[] = [
                    'id'=>$value['id'],
                    'mobile'=>$value['mobile']
                ];
            }
            $param = [
                'kehu_list' => $end_list,
                'opt_userid'=>$this->optUserId,
                'org_kehu_list'=>$org_kehu_list,
            ] ;

            $controller = '\app\common\controller\zhongzhuan\Fenpei';
            $data = call_user_func_array(array($controller, 'addCustomer'), array($param));
            qqq('addCustomer1',$data);
            
//            usleep() 函数延迟执行当前脚本若干微秒（一微秒等于一百万分之一秒）。 延迟5秒
//            usleep(5000000);
        }
        
        
        
        
    }
    
    
    /**
     * 更新客户标签  while  最大 200
     */
    public function ownUpdateKehuLabel(){
        
        while (true){
            
            $yixiang_label_config = [
                'A'=>'84726558','B'=>'84736557','C'=>'84734554','D'=>'84732560','E'=>'84728556','F'=>'84732561'
            ];

            $label_config = [
                '84731318', //客户来源 【新增百应】
            ];

            $list = db('ec_aiuser_to_ecuser')->where(['status'=>1,'label_laiyuan_biaoji_status'=>0,'ecid'=>['>',0]])
                    ->order('id desc')
                    ->where('crmId','<>','')
                    ->limit(200)->select();
            
            if(empty($list)){
                sleep(5);
                continue;
            }
            
            
            $end_list = $item_kehu_ids = $crmIds = [];
            foreach ($list as $value){
                $crmIds[] = $value['crmId'];
                $item_kehu_ids[] = $value['id'];
            }
            
            $param = ['crmIds' => implode(',', $crmIds),'optUserId'=>$this->optUserId,'labels'=>implode(',', $label_config)] ;
            $controller = '\app\common\controller\zhongzhuan\Fenpei';
            $item_response = call_user_func_array(array($controller, 'updateKehuLabel'), array($param));
            qqq('ownUpdateKehuLabel',$item_response);

            if($item_response['code'] == 200){
                db('ec_aiuser_to_ecuser')->where('id','in',$item_kehu_ids)->setField('label_laiyuan_biaoji_status',1);
            }

            
            // usleep() 函数延迟执行当前脚本若干微秒（一微秒等于一百万分之一秒）。 延迟5秒
            usleep(5000000);
        }
        
    }
    
    
    /**
     * 批量变更跟进人 最大50
     */
    public function batchUpdateKehuOwner(){
        while(true){
            
            
            $list = db('ec_aiuser_to_ecuser')->where(['status'=>2,'ecid'=>['>',0]])->limit(50)->select();
            
            if(empty($list)){
                sleep(30);
                continue;
            }

            foreach ($list as $key=>$value){
                $item_crmId = $value['crmId'];
                $item_mobile = $value['mobile'];
                $controller = '\app\common\controller\zhongzhuan\Fenpei';
                $msg_prefix = '[变更跟进人]';

                $save_data = [];
//                if(empty($item_crmId)){
                $item_crm_info = db('ec_kehu')
                        ->field('crmId,follow_userid')
                        ->where(['mobile'=>$item_mobile])->whereNotNull('crmId')->order('id desc')
                        ->find();
                $item_crmId = empty($item_crm_info['crmId']) ? '' : $item_crm_info['crmId'];       

//                $item_org_userid = empty($item_crm_info['follow_userid']) ? '' : $item_crm_info['follow_userid'];
//                }
                
                if(empty($item_crmId)) continue;
               
                $content = json_decode($value['content'],true);
              

                $continue = false;
                $controller = '\app\common\controller\zhongzhuan\Fenpei';
                $item_response = call_user_func_array(array($controller, 'getKehuInfoByCrmId'), array(['crmIds'=>[$item_crmId]]));

                if($item_response['code'] == 200 && !empty($item_response['data'])){
                    foreach ($item_response['data']['list'] as $_v){
                        if($_v['step'] == 4){//合作客户
                            $save_data['status'] = 1;
                            $save_data['tuisong_result_txt'] = $msg_prefix .  '合作客户不作更改';
                            db('ec_aiuser_to_ecuser')->where('id',$value['id'])->update($save_data);
                            $continue = true;
                        }

                        if($content['followUserId'] != $_v['followUserId']){
                             $is_shangban_info = db('ec_user')->field('is_shangban,id')->where('userid',$_v['followUserId'])->find();
                             if(!empty($is_shangban_info) && !empty($is_shangban_info['is_shangban'])){
                                $save_data['ecid'] = $is_shangban_info['id'];
                                $save_data['status'] = 1;
                                $save_data['tuisong_result_txt'] = $msg_prefix .  '跟进人存在不作更改';
                                db('ec_aiuser_to_ecuser')->where('id',$value['id'])->update($save_data);
                                $continue = true;
                            }
                        }else{

                            $save_data['status'] = 1;
                            $save_data['tuisong_result_txt'] = $msg_prefix .  '【自己】此客户已在接收人名下。';
                            db('ec_aiuser_to_ecuser')->where('id',$value['id'])->update($save_data);
                            $continue = true;
                        }
                    }
                }else{
                    $continue = true;
                }

                if($continue)                        continue;
                    
                    
                       
                $step_crm = [];
                
                if(empty($item_crmId)){
                    $save_data['tuisong_result_txt'] = $msg_prefix .  'CrmID不存在';
                }else{
                    $save_data['crmId'] = $item_crmId;
                    
                    if(!empty($content['followUserId'])){
                        $param_owner = ['followUserId'=>$content['followUserId'],'crmIds'=>$item_crmId,'optUserId'=>$this->optUserId];
                        $item_update_owner = call_user_func_array(array($controller, 'updateKehuOwnwer'), array($param_owner));

                        if($item_update_owner['code'] == 200){
                            foreach ($item_update_owner['data']['list'] as $k=>$v){
                                if($v['code'] == 40003 || $v['code'] == 200){
                                    $save_data['status'] = 1;
                                }
                                $save_data['tuisong_result_txt'] = $msg_prefix . $v['msg'];
                            }

                        }else{
                            $save_data['tuisong_result_txt'] = $msg_prefix . '请求失败';
                        }
                    }else{
                        $save_data['tuisong_result_txt'] = $msg_prefix . '跟进人为空';
                    }


                }      


                db('ec_aiuser_to_ecuser')->where('id',$value['id'])->update($save_data);

            }
            

           
           usleep(5000000);
        }
         
    }
    

    /**
    * 放弃客户到公海
    */
    public function batchAbandonKehu(){
        while(true){
            
            
            $list = db('ec_aiuser_to_ecuser')->where(['status'=>2,'ecid'=>0])->limit(200)->select();
            if(empty($list)){
                usleep(5000000);
                continue;
            }
            
            
            $crmIds = [];
            $crmIdNoExistList = [];
            $crmIdExistUpdateList = [];
            foreach ($list as $key=>$value){
                $item_crmId = $value['crmId'];
                $item_mobile = $value['mobile'];
                $controller = '\app\common\controller\zhongzhuan\Fenpei';
                $msg_prefix = '[放弃至公海]';
                
                if(empty($item_crmId)){
                    $crmIdExistUpdateList[$value['id']] = '';
                    $item_crmId = db('ec_kehu')->where(['mobile'=>$item_mobile])->whereNotNull('crmId')->order('id desc')->value('crmId');                    
                }


                if(empty($item_crmId)){
                    $param = ['mobile' => $item_mobile] ;
                    $item_response = call_user_func_array(array($controller, 'getKehuInfoByOptUserid'), array($param));               
                    if($item_response['code'] == 200){
                        $item_data = $item_response['data']['list'][0];
                        $item_crmId = $item_data['crmId'];                   
    //                    $this->updateSignleKehu($item_data);                    
                    }
                }            
                if(empty($item_crmId)){
                    $crmIdNoExistList[] = $value['id'];
                    continue;
                }
                
                if(array_key_exists($value['id'], $crmIdExistUpdateList)){
                    $crmIdExistUpdateList[$value['id']] = $item_crmId;
                }     
                
                $crmIds[] = $item_crmId;

            }
            
            if(!empty($crmIdNoExistList)){
                $msg = $msg_prefix .  'CrmID不存在';
                db('ec_aiuser_to_ecuser')->where('id','in',$crmIdNoExistList)->setField('tuisong_result_txt',$msg);
            }
            
            if(!empty($crmIdExistUpdateList)){
                foreach ($crmIdExistUpdateList as $k =>$v){
                    db('ec_aiuser_to_ecuser')->where('id',$k)->setField('crmId',$v);
                }
            }
            
            if(empty($crmIds)) continue;
            
            
            $param_owner = ['crmIds'=>implode(',', $crmIds),'optUserId'=>$this->optUserId,'type'=>0];
            $item_update_owner = call_user_func_array(array($controller, 'abandonKehu'), array($param_owner));

//             qqq('batchAbandonKehu',$item_update_owner);
            if($item_update_owner['code'] == 200){
                foreach ($item_update_owner['data']['list'] as $k=>$v){
                    if($v['code'] == 40003 || $v['code'] == 200){
                        $save_data['status'] = 1;
                    }
                    $save_data['status_code'] = $v['code'];
                    $save_data['tuisong_result_txt'] = $msg_prefix . $v['msg'];
                    db('ec_aiuser_to_ecuser')->where([
                        'crmId'=>$v['crmId'],
                        'status'=>2
                    ])->update($save_data);
                    
                }

            }
            
            
            
        }
        
    }
    
    
    /**
    * 批量添加跟进记录
    */
    public function batchSaveUserTrajectory(){
        while(true){
            
            
            $zhongzhuan_config  = config('zhongzhuan.field');  
            $baiying_luyin_field_id = $zhongzhuan_config['baiying_luyin']['fieldid'];
                      
            
            $kehu_list = db('ec_aiuser_to_ecuser')->limit(200)->order('id desc')->where(['genjin_status'=>0,'crmId'=>['<>','']])->select();
            qqq('batchSaveUserTrajectory',db('ec_aiuser_to_ecuser')->getLastSql());
            if(empty($kehu_list)){
                sleep(30);
            }
            $list = [];
            foreach ($kehu_list as $value){
                if(empty($value['crmId']))                    continue;
                
                $org_info = json_decode($value['content'],true);

                if(empty($org_info))continue;
                
                
                $luyin_url = $org_info['fields'][$baiying_luyin_field_id];
                
                if(empty($luyin_url)) continue;
                $by_kehu_info = db(getBaiYingDataTable())->field('duration,startTime')->where('id',$value['byid'])->find();

                if(!empty($by_kehu_info)) {
                    $startTime = strlen($by_kehu_info['startTime']) > 10 ?  $by_kehu_info['startTime'] / 1000 : $by_kehu_info['startTime']; 
                    $startTime_date = date("Y年m月d日 H时i分s秒",$startTime);
                    $temp_str = "与{$startTime_date}被拨打电话，拨打时长{$by_kehu_info['duration']}秒；";
                }   
                
                $temp_str = $temp_str . "录音地址:{$luyin_url}" ;

                $list[] = [
                    "id"=>$value['id'],"crmId"=>$value['crmId'],"userId"=>$this->optUserId,"content"=>$temp_str
                ];


            }       
            
            
            if(empty($list)) continue;

            $controller = '\app\common\controller\zhongzhuan\Fenpei';
            $response_data = call_user_func_array(array($controller, 'saveUserTrajectory'), array(['list'=>$list]));
            
            
            if($response_data['code'] == 200){
                $update_data_id = [];
                foreach ($response_data['data'] as $value){
                    if($value['errCode'] == 200){
                        $update_data_id[] = $value['id'];
                    }
                }
                
                
                if(!empty($update_data_id)){
                    $temp = [];
                    $temp['genjin_status'] = 1;
                    $temp['updatetime'] = time();
                    db('ec_aiuser_to_ecuser')->where("id",'in',$update_data_id)->update($temp);
                }
            }
            
            
        }
        
        
    }
    
    /**
     * 批量获取crmid
     */
    public function batchGetKeHhCrmByMobile(){
        while(true){
            
            $list = db('ec_aiuser_to_ecuser')->limit(50)->where('crmId','')->where('repeat_count',0)->order('id desc')->select();
            if(empty($list)){
//                sleep(30);
            }
            $mobile = [];
            foreach ($list as $key=>$value){
                $info = db('ec_kehu')->field('crmId,mobile')
                        ->whereNotNull('crmId')
                        ->where('mobile',$value['mobile'])->order('id desc')->find();
                if(!empty($info)){
                    db('ec_aiuser_to_ecuser')->where('id',$value['id'])->setField('crmId',$info['crmId']);
                }else{
                    $mobile[] = $value['mobile'];
                }
                
            }
            
            
            if(empty($mobile)) continue;
            

           $param = ['mobile' => implode(',', $mobile)] ;
           qqq('batchGetKeHhCrmByMobile9',$mobile);
           $controller = '\app\common\controller\zhongzhuan\Fenpei';
           $item_response = call_user_func_array(array($controller, 'getKehuInfoByOptUserid'), array($param));          
           qqq('batchGetKeHhCrmByMobile8',$item_response);
           if($item_response['code'] == 200){
               $insert_data = [];
               
               foreach ($item_response['data']['list'] as $value){
                   
                   $item_mobile = $value['mobiles'];
                   $item_crmId = $value['crmId'];       
                   if(empty($item_mobile)) continue;
                   
                   db('ec_aiuser_to_ecuser')->where(['mobile'=>['in',$item_mobile],'crmId'=>''])->setField('crmId',$item_crmId);
                   foreach ($item_mobile as $k =>$v){
                       $middle_data = [];
                       $count = db('ec_kehu')->where(['mobile'=>$v])->count();
                        if(!empty($count)){
                            db('ec_kehu')->where(['mobile'=>$v])->setField('crmId',$item_crmId);
                        }else{
                            $middle_data['follow_userid'] = empty($value['followUserId'])? 0 : $value['followUserId']; 
                             $middle_data['mobile'] = $v;                
                             $middle_data['crmId'] =$item_crmId;
                             $middle_data['name'] = $value['name'];
                             $middle_data['content'] = json_encode($value,JSON_UNESCAPED_UNICODE);
                             $middle_data['createtime'] = time();
                             $insert_data[] = $middle_data;                        
                        }
                   }
                   
                   
                   
               }
               if(!empty($insert_data)){
                   db('ec_kehu')->insertAll($insert_data);
               }
           }else{
//               db('ec_aiuser_to_ecuser')->where(['mobile'=>['in',$item_mobile],'crmId'=>''])->setField('repeat_count',1);
           }
           
        }
         
    }
    
   
    
  
}
